package com.sky.utils;

import com.sky.constant.MessageConstant;
import com.sky.properties.LocalUploadProperties;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Component
@Slf4j
@Data
public class LocalUploadUtil {

    @Autowired
    private LocalUploadProperties localUploadProperties;
    public String upload(MultipartFile file) {
        // 原始文件名
        String originalFilename = file.getOriginalFilename();
        // 截取原始文件名后缀
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 构造新文件名称
        String objectName = UUID.randomUUID().toString() + extension;

        File folder = new File(localUploadProperties.getBasePath());

        if(!folder.exists()){
            folder.mkdirs();
        }
        try {
            file.transferTo(new File(folder , objectName));
            return "http://" + localUploadProperties.getHost()+":"+localUploadProperties.getPort()+"/img/"+objectName;
        } catch (IOException e) {
            log.error("文件上传失败：{}",e);
            return MessageConstant.UPLOAD_FAILED;
        }
    }
}
